package com.xique.door.device.freeview.service.biz;

import com.alibaba.fastjson.JSONObject;

import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.dto.CardDeviceHouseCodeDTO;
import com.xique.door.bean.dto.EstateUserDownDTO;
import com.xique.door.bean.dto.UserDeviceHouseCodeDTO;
import com.xique.door.constant.AccessCommandConstant;
import com.xique.door.device.command.AccessCommandFreeviewService;
import com.xique.door.device.freeview.util.SnowflakeIdWorker;
import com.xique.door.device.hq.bean.dto.HQResultDTO;
import com.xique.door.device.hq.bean.dto.HQResultDataDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: caogangquan
 * @Date: 2021/10/22 18:05
 * @Description:
 */
@Service
public class FreeviewCommandBizService {

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    private FreeviewEventBizService freeviewEventBizService;

    @Autowired
    private AccessCommandFreeviewService accessCommandFreeviewService;

    /**
     * @description: 下发单个人员
     * @author caogq
     * @date 2021/11/12 9:19
     * @version 1.0
     */
    public Object downUserInfo(List<String> devSns, User user) {
        //事件编号：雪花算法，生成分布式唯一id
        return accessCommandFreeviewService.downUserInfo(devSns, user);
    }

    /**
     * @description: 批量下发人员
     * @author caogq
     * @date 2021/11/12 9:19
     * @version 1.0
     */

    public Object downUserInfos(List<AccessDevice> accessDevices, List<User> users, List<UserDeviceHouseCodeDTO> dtos) {
        //事件编号：雪花算法，生成分布式唯一id
        return accessCommandFreeviewService.downUserInfos(accessDevices, users,dtos);
    }

    public Object downVisitorInfos(List<AccessDevice> accessDevices, List<Visitor> visitors) {
        //事件编号：雪花算法，生成分布式唯一id
        return accessCommandFreeviewService.downVisitorInfos(accessDevices, visitors);
    }

    public Object downCardInfos(List<AccessDevice> accessDevices, List<DCard> cards, List<CardDeviceHouseCodeDTO> dtos) {
        //事件编号：雪花算法，生成分布式唯一id
        return accessCommandFreeviewService.downCardInfos(accessDevices, cards, dtos);
    }

    public Object downEstateUserInfos(List<AccessDevice> accessDevices, List<EstateUserDownDTO> users) {
        //事件编号：雪花算法，生成分布式唯一id
        return accessCommandFreeviewService.downEstateUserInfos(accessDevices, users);
    }

    public Object downEstateUserCardInfos(List<AccessDevice> accessDevices, List<EstateUserDownDTO> users) {
        //事件编号：雪花算法，生成分布式唯一id
        return accessCommandFreeviewService.downEstateUserCardInfos(accessDevices, users);
    }

    public Object deleteEstateUserInfos(List<String> devSns, List<EstateUserDownDTO> users) {
        return accessCommandFreeviewService.deleteEstateUserInfos(devSns, users);
    }

    public Object deleteEstateUserCardInfos(List<String> devSns, List<EstateUserDownDTO> users) {
        return accessCommandFreeviewService.deleteEstateUserCardInfos(devSns, users);
    }


    /**
     * @description: 删除单个用户（将批量和单用户操作分开，后续单用户要做同步）
     * @author caogq
     * @date 2021/11/11 17:32
     * @version 1.0
     */
    public Object deleteUserInfo(List<String> devSns, User user) {

        return accessCommandFreeviewService.deleteUser(devSns, user);
    }


    /**
     * @description: 删除单个用户（将批量和单用户操作分开，后续单用户要做同步）
     * @author caogq
     * @date 2021/11/11 17:32
     * @version 1.0
     */

    public Object deleteUserInfos(List<String> devSns, List<User> users) {

        return accessCommandFreeviewService.deleteUsers(devSns, users);
    }

    public Object deleteVisitorInfos(List<String> devSns, List<Visitor> visitors) {

        return accessCommandFreeviewService.deleteVisitors(devSns, visitors);
    }

    public Object deleteVisitorInfo(List<String> devSns, Visitor visitor) {

        return accessCommandFreeviewService.deleteVisitor(devSns, visitor);
    }

    /**
     * @description: 下发访客
     * @author caogq
     * @date: 2021/11/18 11:19
     * @Param
     */

    @Deprecated
    public Object downVisitorInfo(List<String> devSns, Visitor visitor) {
        //事件编号：雪花算法，生成分布式唯一id
        return accessCommandFreeviewService.downVisitorInfo(devSns, visitor);
    }


    /**
     * @description: 下发单个卡片
     * @author caogq
     * @date 2021/11/12 9:19
     * @version 1.0
     */

    public Object downCardInfo(List<String> devSns, DCard card, List<CardDeviceHouseCodeDTO> dtos) {
        return accessCommandFreeviewService.downCardInfo(devSns,card,dtos);
    }

    /**
     * @description: 批量下发卡
     * @author caogq
     * @date 2021/11/12 9:19
     * @version 1.0
     */
    @Deprecated
    public Object downCardInfos(List<String> devSns, List<DCard> dCards) {
        return null;
    }

    /**
     * @description: 删除单个卡
     * @author caogq
     * @date 2021/11/12 9:19
     * @version 1.0
     */

    public Object deleteCardInfo(List<String> devSns, DCard dCard) {
        return accessCommandFreeviewService.deleteCardInfo(devSns,dCard);
    }

    /**
     * @description: 批量删除卡
     * @author caogq
     * @date 2021/11/12 9:19
     * @version 1.0
     */

    public Object deleteCardInfos(List<String> devSns, List<DCard> dCards) {
        return accessCommandFreeviewService.deleteCardInfos(devSns,dCards);
    }

    /**
     * @description: 更新卡
     * @author caogq
     * @date 2021/11/16 15:14
     * @version 1.0
     */

    public Object updateCardInfo(List<String> devSns, DCard card) {
        return accessCommandFreeviewService.updateCardInfo(devSns,card);
    }

    /**
     * @description: 挂失卡
     * @author caogq
     * @date 2021/11/16 15:14
     * @version 1.0
     */

    public Object lostCardInfo(List<String> devSns, DCard card) {
        return accessCommandFreeviewService.lostCardInfo(devSns,card);
    }

    /**
     * @description:
     * @author caogq
     * @date: 2021/11/5 13:42
     * @Param url 固件地址 ； md5 固件哈希值
     */
    public Object upgrade(String devSn, String url, String md5) {
        //事件编号
        String eventId = String.valueOf(snowflakeIdWorker.nextId());
        return accessCommandFreeviewService.freeviewUpgrade(eventId, devSn, url, md5);
    }

    /**
     * @param devSn
     * @param rangeTimes
     * @description: 设置设备屏息
     * @author taojc
     * @date: 2022/9/2
     */
    public Object screenSave(String devSn,List<String> rangeTimes){
        //事件编号
        String eventId = String.valueOf(snowflakeIdWorker.nextId());
        return accessCommandFreeviewService.screenSave(eventId,devSn,rangeTimes);
    }

    /**
     * @description:
     * @author caogq
     * @date: 2021/11/5 13:42
     * @Param url 固件地址 ； md5 固件哈希值
     */
    public Object reboot(String devSn) {
        //事件编号
        String eventId = String.valueOf(snowflakeIdWorker.nextId());
        return accessCommandFreeviewService.freeviewReboot(eventId,devSn);
    }

    /**
     * @description:
     * @author caogq
     * @date: 2021/11/5 13:42
     * @Param url 固件地址 ； md5 固件哈希值
     */
    public AjaxResult remoteOpenDoor(AccessDevice accessDevice, String operator) {
        if(StringUtils.isEmpty(accessDevice.getOnlineStatus()) || "offline".equals(accessDevice.getOnlineStatus())){
            return AjaxResult.error("设备离线");
        }
        Object obj = accessCommandFreeviewService.freeviewRemoteOpenDoor(accessDevice.getDevSn(), operator);
        AjaxResult returnHQ = this.getReturnHQ(JSONObject.parseObject(obj.toString(), HQResultDTO.class), AccessCommandConstant.FromType.ADMIN);
        if (returnHQ.get("code").equals(AjaxResult.Type.ERROR)){
            return returnHQ;
        }

        return AjaxResult.success();
    }

    /**
     * 获取返回值
     * @author shd
     * @date 2021/7/8 9:48
     * @param dto
     * @param fromType 来源类型
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    private AjaxResult getReturnHQ(HQResultDTO dto, String fromType) {
        if (0 != dto.getResult_code()) {
            return AjaxResult.error("下发失败");
        }
        List<String> successMsgList = new ArrayList<>();
        List<String> errorMsgList = new ArrayList<>();

        if(null != dto && null != dto.getData()){
            for (HQResultDataDTO data : dto.getData()) {
                String message = "";
                if (!data.getStatus().equals(AccessCommandConstant.DeviceStatus.SUCCESS)) {
                    message = data.getDeviceCode() + ":" + data.getMsg() + (data.getResult() != null ?  " 具体原因：" + data.getResult().getInfo().getDetail() : "") + "<br/>";
                    errorMsgList.add(message);
                } else {
                    message = data.getDeviceCode() + ":" + data.getMsg() + "<br/>";
                    successMsgList.add(message);
                }
            }
        }
        //TODO
        if(null != dto && null != dto.getData_obj()){

        }
        String successMsg = StringUtils.join(successMsgList, "");
        String errorMsg = StringUtils.join(errorMsgList, "");
        StringBuilder returnMsg = new StringBuilder();
        if (StringUtils.isNotEmpty(errorMsg)){
            returnMsg.append("失败下发设备如下：<br/>" + errorMsg + "<br/>");
        }
        if (StringUtils.isNotEmpty(successMsg)){
            returnMsg.append( "成功下发设备如下：<br/>" + successMsg);
        }
//        String returnMsg = "失败下发设备如下：<br/>" + errorMsg +  "<br/>成功下发设备如下：<br/>" + successMsg;
        if (AccessCommandConstant.FromType.APP.equals(fromType)) {
            StringUtils.replace(returnMsg.toString(), "<br/>", "\n");
        }
        if (!errorMsgList.isEmpty()) {
            return AjaxResult.success(returnMsg.toString());
        }
        return AjaxResult.success(returnMsg.toString());
    }

    /**
     * @description: 下发或者删除广告
     * @author caogq
     * @date: 2022/3/9 15:25
     */
    public Object downAdvertisements(DAdvert advert, List<String> devSns, Integer operationType){
        return accessCommandFreeviewService.downAdvertisements(advert,devSns,operationType);
    }

}
